#    MythMobile, a Django interface to MythTV for mobile devices
#    Copyright (C) 2011 Andrew Wilkinson (andrewjwilkinson@gmail.com)
#
#     This program is free software; you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation; either version 2 of the License, or
#     (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License along
#     with this program; if not, write to the Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import os
import threading

import _mythmobile
def get_next_file(base_filename, file_list):
    i = 0
    while True:
        yield "%s-%i.mpg" % (base_filename, i)

        file_list.append("%s-%i.mpg" % (base_filename, i))

        i += 1

class Segmenter(threading.Thread):
    def __init__(self, base_filename, end_process_func, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)

        self.base_filename = base_filename
        self.end_process_func = end_process_func
        self.packet = 0
        self.packets = {}

        self.files = []

    def add_packet(self, packet):
        assert len(packet) == 4096

        self.packets[self.packet] = packet
        self.packet += 1

        if self.packet == 5:
            self.start()

    def run(self):
        self.next_file_func = get_next_file(self.base_filename, self.files)

        try:
            self.segmenter = _mythmobile.Segment("tv.mpg", self.next_file_func, self.packets, 10)

            while True:
                try:
                    self.segmenter.process()
                except SystemError, e:
                    print e
                    continue
                else:
                    break
        finally:
            self.end_process_func()

    def delete_files(self):
        # Ensure that the current file segment is in the file list
        self.next_file_func.next()

        for f in self.files:
            print "delete", f
            os.remove(f)
